package com.predict.javademo.services.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.predict.javademo.entity.attackAlgParams.BasicParam;
//import com.predict.javademo.mapper.LogIntoResultMapper;
import com.predict.javademo.mapper.LogResultMapper;
import com.predict.javademo.result.AdversarialResult;
import com.predict.javademo.result.DefenseResult;
import com.predict.javademo.result.OriginalResult;
import com.predict.javademo.services.PredictApiService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.*;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedReader;
import java.io.IOException;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Map;


@Service
@Slf4j
public class PredictApiServiceImpl implements PredictApiService {

    @Autowired
    private RestTemplate restTemplate;

    @Autowired
    private LogResultMapper logResultMapper;

    private static final String ORIGINAL = "original";
    private static final String ADVERSARIAL = "adversarial";
    private static final String DEFENSE = "defense";

    @Value("${flask.url.alg}")
    private String algUrl;

    @Value("${flask.url.predict}")
    private String predictUrl;

    @Override
    public ResponseEntity handle(HttpServletRequest request, HttpServletResponse response) {
        log.debug("开始处理前端参数");

        StringBuilder json = new StringBuilder();
        try (BufferedReader reader = request.getReader()) {
            String line;
            while ((line = reader.readLine()) != null) {
                json.append(line);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        BasicParam bp = JSON.parseObject(json.toString(), BasicParam.class);
        log.debug("前端参数为:{}",bp);
        //去除前缀
        bp.getAttach().entrySet().forEach(entry -> {
            if(entry.getKey().equals("targetImage")){
                if (entry.getValue().startsWith("data:image")) {
                    entry.setValue(entry.getValue().substring((entry.getValue().indexOf(",")) + 1));
                }
            }
        });
        ResponseEntity<Map> result = restTemplate.postForEntity(algUrl, bp, Map.class);
        log.debug("收到flask返回数据");
        logResultIntoDataBase(result);

        return new ResponseEntity<>(result.getBody(), HttpStatus.OK);
    }

//    @Async
    public void logResultIntoDataBase(ResponseEntity<Map> result){
        log.debug("开始异步录入数据：{}",result.getBody());
        String jsonString = JSON.toJSONString(result.getBody());
        String currentTime = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date());
        logResultMapper.logResult(jsonString, currentTime);
    }
}
